package main

import (
	"log"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

// StatCost 自定义中间件，统计请求处理耗时
func StatCost() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		// 继续处理请求
		c.Next()
		end := time.Now()
		p := end.Sub(start)
		log.Printf("请求处理耗时: %v", p)
	}
}

// 前置处理函数，设置键值
func SetName() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Set("name", "Jane")
		c.Next()
	}
}

func main() {
	r := gin.New()
	r.Use(StatCost())

	r.GET("/test", SetName(), func(c *gin.Context) {
		name := c.MustGet("name").(string)
		log.Println(name)
		c.JSON(http.StatusOK, gin.H{
			"message": "Hello world!",
		})
	})
	r.Run()
}
